package cn.sinata.wanglin.neighbor.view;

import android.annotation.TargetApi;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Build;
import android.support.v4.content.ContextCompat;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextPaint;
import android.text.TextUtils;
import android.text.style.AbsoluteSizeSpan;
import android.text.style.ClickableSpan;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.facebook.drawee.backends.pipeline.Fresco;
import com.facebook.drawee.interfaces.DraweeController;
import com.facebook.drawee.view.SimpleDraweeView;
import com.facebook.imagepipeline.common.ResizeOptions;
import com.facebook.imagepipeline.request.ImageRequest;
import com.facebook.imagepipeline.request.ImageRequestBuilder;
import com.hyphenate.easeui.utils.EaseSmileUtils;
import com.xilada.xldutils.adapter.ListAdapter;
import com.xilada.xldutils.utils.ActivityUtil;
import com.xilada.xldutils.utils.DensityUtil;
import com.xilada.xldutils.utils.DialogUtils;
import com.xilada.xldutils.utils.SharedPreferencesUtils;
import com.xilada.xldutils.utils.TimeUtils;
import com.xilada.xldutils.utils.Utils;
import com.xilada.xldutils.view.ExpandableHeightGridView;
import com.xilada.xldutils.view.ExpandableHeightListView;
import com.xilada.xldutils.view.utils.ViewHolder;

import java.util.ArrayList;
import java.util.List;

import cn.sinata.wanglin.R;
import cn.sinata.wanglin.commonutils.Constant;
import cn.sinata.wanglin.model.Circle;
import cn.sinata.wanglin.model.Comment;
import cn.sinata.wanglin.model.Image;
import cn.sinata.wanglin.model.Like;
import cn.sinata.wanglin.neighbor.activity.ShowImagePagerActivity;
import cn.sinata.wanglin.neighbor.controller.FriendCircleListener;
import cn.sinata.wanglin.neighbor.controller.OnImageClickListener;
import cn.sinata.wanglin.neighbor.controller.UserCircleController;
import cn.sinata.wanglin.utils.CustomLinkMovementMethod;

/**
 * 圈子视图
 * Created by liaoxiang on 16/12/13.
 */

public class UserCircleView extends RelativeLayout implements UserCircleController {
    private final int MAX_COMMENT_NUM = 5;
    private TextView timeView;
    private TextView textContentView;
    private TextView textAllContent;
    private TextView commentNumView;//评论按钮
    private TextView praiseNamesView;//点赞人
    private TextView dateView;
    private ExpandableHeightGridView imageGrid;
    private ExpandableHeightListView commentsList;
    private TextView allCommentNumView;//全部评论
    private TextView deleteView;//删除按钮
    private View ll_comment_and_praise;
    private int smallImageSize;
    private int largeImageSize;
    private int paddingSize;
    private String userId;

    private FriendCircleListener listener;

    public UserCircleView(Context context) {
        super(context);
        init(context, null, 0, 0);
    }

    public UserCircleView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context, attrs, 0, 0);
    }

    public UserCircleView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context, attrs, defStyleAttr, 0);
    }

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    public UserCircleView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
        init(context, attrs, defStyleAttr, defStyleRes);
    }

    void init(Context context,AttributeSet attrs, int defStyleAttr, int defStyleRes){
        LayoutInflater.from(context).inflate(R.layout.user_circle_composite_view, this, true);

        if (isInEditMode()){
            return;
        }
        userId = SharedPreferencesUtils.getString(Constant.SP_USERID);

        timeView = findView(R.id.timeView);
        dateView = findView(R.id.tv_time);
        textContentView = findView(R.id.textContentView);
        textAllContent = findView(R.id.textAllContent);
        imageGrid = findView(R.id.imageGrid);
        commentNumView = findView(R.id.tv_comment);
        dateView = findView(R.id.tv_time);
        commentsList = findView(R.id.commentList);
        allCommentNumView = findView(R.id.tv_all_comment);
        deleteView = findView(R.id.deleteView);
        praiseNamesView = findView(R.id.tv_praise_names);
        ll_comment_and_praise = findView(R.id.ll_comment_and_praise);
        smallImageSize = DensityUtil.dip2px(context,80);
        paddingSize = DensityUtil.dip2px(context,8);
        //大图除去头像和间隔，剩余部分的2分之一大小
//        largeImageSize = (int)((DensityUtil.getDeviceWidth(context)
//                -DensityUtil.dip2px(context,24))*0.5f);
        largeImageSize = 2*smallImageSize+paddingSize;


    }

    private <T extends View> T findView(int resId){
        //noinspection unchecked
        return (T)findViewById(resId);
    }

    public void setListener(FriendCircleListener listener){
        this.listener = listener;
    }

    @Override
    public void update(final int position, final Circle friendCircle,long pTime) {

        timeView.setText(TimeUtils.getTimeInterval(friendCircle.getTime(),friendCircle.getSystemTime()));
        //如果文本内容不为空，设置文本。
        if (!TextUtils.isEmpty(friendCircle.getText())){
            Spannable span = EaseSmileUtils.getSmallSmiledText(getContext(), friendCircle.getText());
            textContentView.setText(span, TextView.BufferType.SPANNABLE);
        }
        String time = TimeUtils.getCurrentTimeDDMM(friendCircle.getTime());
        if (position==0){
            dateView.setVisibility(View.VISIBLE);
        }else {
            String preTime = TimeUtils.getCurrentTimeDDMM(pTime);
            dateView.setVisibility(TextUtils.equals(time,preTime)?View.INVISIBLE:View.VISIBLE);
        }
        SpannableString s = new SpannableString(time);
        s.setSpan(new AbsoluteSizeSpan(14,true), 2, s.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);  //第二个参数boolean dip，如果为true，表示前面的字体大小单位为dip，否则为像素，同上。
        dateView.setText(s);
        //如果文本内容不为空则显示
        textContentView.setVisibility(TextUtils.isEmpty(friendCircle.getText())?GONE:VISIBLE);

        int lineCount = friendCircle.getContentLineCount();
        //如果没有测量过这条消息的行数。
        if (lineCount == -1) {
//            textContentView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
//
//                @Override
//                public void onGlobalLayout() {
//                    // TODO Auto-generated method stub
//                    Utils.systemErr("行数" + textContentView.getLineCount());
//                    textContentView.getViewTreeObserver().removeGlobalOnLayoutListener(this);
//                    if (textContentView.getLineCount() > 0 && Build.VERSION.SDK_INT >= 16) {
//                        textContentView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
//                    }
//                    int lineCount = textContentView.getLineCount();
//                    friendCircle.setContentLineCount(lineCount);
//
//                    textAllContent.setVisibility(lineCount>5?VISIBLE:GONE);
//                    textAllContent.setText(friendCircle.isShowAll()?"收起":"全文");
//                    if (lineCount > 5) {
//                        textContentView.setMaxLines(friendCircle.isShowAll()?lineCount:5);
//                    } else {
//                        textContentView.setMaxLines(5);
//                    }
//                }
//            });
            textContentView.post(new Runnable() {
                @Override
                public void run() {
                    Circle circle ;
                    int lineCount = textContentView.getLineCount();
                    if (textContentView.getTag() != null) {
                        circle = (Circle) textContentView.getTag();
                    } else {
                        circle = friendCircle;
                    }
                    circle.setContentLineCount(lineCount);
                    textAllContent.setVisibility(lineCount > 5 ? VISIBLE : GONE);
                    textAllContent.setText(friendCircle.isShowAll() ? "收起" : "全文");
                    if (lineCount > 5) {
                        textContentView.setMaxLines(friendCircle.isShowAll() ? lineCount : 5);
                    } else {
                        textContentView.setMaxLines(5);
                    }
                }
            });
        } else {
            textAllContent.setVisibility(lineCount>5?VISIBLE:GONE);
            textAllContent.setText(friendCircle.isShowAll()?"收起":"全文");
            if (lineCount > 5) {
                textContentView.setMaxLines(friendCircle.isShowAll()?lineCount:5);
            } else {
                textContentView.setMaxLines(5);
            }
        }

        textAllContent.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                boolean showAll = friendCircle.isShowAll();
                friendCircle.setShowAll(!showAll);
//                textAllContent.setText(friendCircle.isShowAll()?"收起":"全文");
//                int lineCount = friendCircle.getContentLineCount();
//                textContentView.setMaxLines(friendCircle.isShowAll()?lineCount:5);
                if (listener != null) {
                    listener.showAllToggle();
                } else {
                    textAllContent.setText(friendCircle.isShowAll()?"收起":"全文");
                    int lineCount = friendCircle.getContentLineCount();
                    textContentView.setMaxLines(friendCircle.isShowAll()?lineCount:5);
                }
            }
        });

        if (TextUtils.equals(userId, friendCircle.getAuthorId())) {
            deleteView.setVisibility(VISIBLE);
        } else {
            deleteView.setVisibility(GONE);
        }

        if (friendCircle.getLikeNum() <= 0 && friendCircle.getCommentNum() <= 0) {
            ll_comment_and_praise.setVisibility(GONE);
        } else {
            ll_comment_and_praise.setVisibility(VISIBLE);
        }

        if (friendCircle.getLikeNum() > 0) {
            String praiseText = getPraiseNames(friendCircle);
            if (friendCircle.getLikeNum() > 4) {
                praiseText += "等"+friendCircle.getLikeNum()+"人觉得很赞";
            }
            Utils.systemErr("-->"+praiseText);
            praiseNamesView.setText(praiseText);
            praiseNamesView.setVisibility(VISIBLE);
        } else {
            praiseNamesView.setVisibility(GONE);
        }

        //设置图片
        setImageLayout(friendCircle);
        setCommentsLayout(friendCircle.getCommentNum(),friendCircle.getCommentList());
//        commentNumView.setText(String.valueOf(friendCircle.getCommentNum()));
        allCommentNumView.setText(getContext().getString(R.string.all_comment_num_string,friendCircle.getCommentNum()));

        commentNumView.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!TextUtils.isEmpty(friendCircle.getId())) {
                    showPopup(v,position,friendCircle);
                }
            }
        });
        deleteView.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                deleteDialog(position,friendCircle);
            }
        });

    }

    void deleteDialog(final int position, final Circle circle){
        DialogUtils.createNoticeDialog(getContext(), "请注意", "您确定要删除当前信息么？", "确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                if (listener != null) {
                    listener.onDelete(position,circle.getId());
                }
            }
        });
    }

    private void setImageLayout(final Circle circle){
        List<Image> urls = circle.getImages();
        if (urls==null){
            imageGrid.setVisibility(GONE);
            return;
        }
        imageGrid.setVisibility(urls.size()>0?VISIBLE:GONE);
        imageGrid.setExpanded(true);
        //多于1张图片
        if (urls.size()>1 && urls.size() != 4){
            imageGrid.setNumColumns(3);
            imageGrid.setColumnWidth(smallImageSize);
            imageGrid.getLayoutParams().width = smallImageSize*3+2*paddingSize;
        } else if (urls.size() == 4) {
            imageGrid.setNumColumns(2);
            imageGrid.setColumnWidth(smallImageSize);
            imageGrid.getLayoutParams().width = smallImageSize*2+paddingSize;
        } else {
            imageGrid.setNumColumns(1);
            imageGrid.setColumnWidth(largeImageSize);
            imageGrid.getLayoutParams().width = largeImageSize;
        }
        ImageAdapter imageAdapter = new ImageAdapter(getContext(),urls,urls.size()==1);
        imageAdapter.setOnImageClickListener(new OnImageClickListener() {
            @Override
            public void onClick(View view, int position) {
                ActivityUtil.create(getContext())
                        .go(ShowImagePagerActivity.class)
                        .put(ShowImagePagerActivity.DATA,circle)
                        .put(ShowImagePagerActivity.POSITION,position)
                        .start();
            }
        });
        imageGrid.setAdapter(imageAdapter);
    }

    private void setCommentsLayout(int size,List<Comment> comments){
        if (comments == null){
            commentsList.setVisibility(GONE);
            return;
        }
        commentsList.setVisibility(comments.size()>0?VISIBLE:GONE);
        allCommentNumView.setVisibility(size>MAX_COMMENT_NUM?VISIBLE:GONE);
        commentsList.setExpanded(true);
        List<Comment> temp ;
        if (comments.size()>MAX_COMMENT_NUM){
            temp = new ArrayList<>();
            temp.addAll(comments.subList(0,MAX_COMMENT_NUM));
        }else {
            temp = new ArrayList<>();
            temp.addAll(comments);
        }
        commentsList.setAdapter(new CommentAdapter(getContext(),temp));

    }

    private class ImageAdapter extends ListAdapter<Image> {

        private boolean single = false;
        private List<Image> list;
        /**
         * 列表适配器
         *
         * @param ctx      上下文
         * @param list     数据list
         */
        public ImageAdapter(Context ctx, List<Image> list,boolean single) {
            super(ctx, list, R.layout.item_image);
            this.single = single;
            this.list = list;
        }

        @Override
        protected void onBind(final int position, Image data, ViewHolder holder) {
            SimpleDraweeView draweeView = holder.bind(R.id.image);
            Uri uri = Uri.parse(data.getUrl());
            //头像设置freso参数
            if (single){
                ImageRequest request = ImageRequestBuilder.newBuilderWithSource(uri)
                        .setLocalThumbnailPreviewsEnabled(true)
                        .setAutoRotateEnabled(true)
//                        .setResizeOptions(new ResizeOptions(smallImageSize,smallImageSize))
                        .build();
                DraweeController controller = Fresco.newDraweeControllerBuilder()
                        .setImageRequest(request)
                        .setOldController(draweeView.getController())
                        .build();
                draweeView.setController(controller);
                draweeView.setAspectRatio(data.getRatio());
            }else {
                ImageRequest request = ImageRequestBuilder.newBuilderWithSource(uri)
                        .setLocalThumbnailPreviewsEnabled(true)
                        .setAutoRotateEnabled(true)
                        .setResizeOptions(new ResizeOptions(smallImageSize,smallImageSize))
                        .build();
                DraweeController controller = Fresco.newDraweeControllerBuilder()
                        .setImageRequest(request)
                        .setOldController(draweeView.getController())
                        .build();
                draweeView.setController(controller);
                draweeView.setAspectRatio(1.0f);
            }

            draweeView.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (listener != null) {
                        listener.onClick(v,position);
                    }
                }
            });

        }
        public void setOnImageClickListener(OnImageClickListener listener){
            this.listener = listener;
        }

        private OnImageClickListener listener;
    }

    private class CommentAdapter extends ListAdapter<Comment>{

        /**
         * 列表适配器
         *
         * @param ctx      上下文
         * @param list     数据list
         */
        public CommentAdapter(Context ctx, List<Comment> list) {
            super(ctx, list, R.layout.item_comment_view);
        }

        @Override
        protected void onBind(final int position, final Comment data, ViewHolder holder) {
            TextView content = holder.bind(R.id.tv_content);
            CustomLinkMovementMethod linkMovementMethod = new CustomLinkMovementMethod();
            linkMovementMethod.setOnTextClickListener(new CustomLinkMovementMethod.TextClickedListener() {
                @Override
                public void onTextClicked() {
                    if (listener!=null) {
                        listener.onCommentItemClick(position, data);
                    }
                }
            });
            content.setMovementMethod(linkMovementMethod);
            StringBuilder builder = new StringBuilder();
            String fromNick = data.getFromNick();
            builder.append(fromNick);
            TextClickableSpan from = new TextClickableSpan(fromNick);
            TextClickableSpan to = null;
            String toNick = data.getToNick();
            //类型（0评论文章,1回复评论）
            if (data.getType() == 1 && !TextUtils.equals(data.getParentID(),data.getId())){
                builder.append("回复");
                builder.append(toNick);
                to = new TextClickableSpan(toNick);
            }
            builder.append(":");
            builder.append(data.getContent());

//            SpannableString spannableString = new SpannableString(builder.toString());
            Spannable spannableString = EaseSmileUtils.getSmallSmiledText(getContext(),builder.toString());
            if (fromNick != null) {
                spannableString.setSpan(from,0,fromNick.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            }
            if (to!=null){
                spannableString.setSpan(to,fromNick.length()+2,fromNick.length()+2+toNick.length(),Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            }
            content.setText(spannableString);
        }
    }

    private class TextClickableSpan extends ClickableSpan {
        private String id;
        public TextClickableSpan(String id){
            this.id = id;
        }

        @Override
        public void onClick(View widget) {
            if (listener!=null){
                listener.onLinkNameClick(id);
            }

        }

        @Override
        public void updateDrawState(TextPaint ds) {
            if (listener!=null) {
//                ds.setColor(ContextCompat.getColor(getContext(),R.color.blue_15));
                ds.setColor(ContextCompat.getColor(getContext(),R.color.textColor));
            }else {
                ds.setColor(ContextCompat.getColor(getContext(),R.color.textColor));
            }
            ds.setUnderlineText(false);
        }
    }

    private String getPraiseNames(Circle circle){
        StringBuilder  name = new StringBuilder();
        if (circle.getLikeList() == null || circle.getLikeList().size()==0) {
            return name.toString();
        }
        for (Like like : circle.getLikeList()) {
            name.append(like.getAuthorNick());
            name.append(",");
        }
        if (name.length() > 0) {
            name.deleteCharAt(name.length()-1);
        }
        return name.toString();
    }

    void showPopup(View parent, final int position, final Circle circle){
        final PopupWindow popupWindow = new PopupWindow(getContext());
        View view = View.inflate(getContext(),R.layout.popup_comment_and_like,null);
        View tv_comment = view.findViewById(R.id.tv_comment);
        TextView tv_like = (TextView) view.findViewById(R.id.tv_like);
        view.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
        if (circle.getClickPraise() == 1) {
            tv_like.setText("取消");
        } else {
            tv_like.setText("点赞");
        }
        tv_comment.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                if (popupWindow != null && popupWindow.isShowing()) {
                    popupWindow.dismiss();
                }

                if (listener != null) {
                    Comment comment = new Comment();
                    comment.setFromNick(circle.getAuthorNick());
                    comment.setId(circle.getAuthorId());
                    listener.onCommentButtonClick(position,comment);
                }
            }
        });
        tv_like.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                if (popupWindow != null && popupWindow.isShowing()) {
                    popupWindow.dismiss();
                }
                if (listener != null) {
                    if (!TextUtils.isEmpty(circle.getId())) {
                        listener.onPraiseButtonClick(position, circle.getId());
                    }
                }
            }
        });

        popupWindow.setWidth(LayoutParams.WRAP_CONTENT);
        popupWindow.setHeight(LayoutParams.WRAP_CONTENT);
        popupWindow.setContentView(view);
        popupWindow.setTouchable(true);
        popupWindow.setFocusable(true);
        popupWindow.setBackgroundDrawable(new BitmapDrawable(getResources(),(Bitmap) null));
        popupWindow.setOutsideTouchable(true);
        int[] location = new int[2];
        parent.getLocationOnScreen(location);
        view.measure(MeasureSpec.UNSPECIFIED,MeasureSpec.UNSPECIFIED);
        int width = view.getMeasuredWidth();
        popupWindow.showAtLocation(parent,Gravity.NO_GRAVITY, location[0]-width,location[1]);
    }
}
